﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Innovator
{
	public class ComponentCollection : Collection<Component>
	{
		GameScreen owner;
		List<int> inDrawOrder = new List<int>();
		public ComponentCollection(GameScreen Owner)
		{
			owner = Owner;
		}
		protected override void InsertItem(int index, Component item)
		{
			if (item.Parent != null && item.Parent != owner)
				item.Parent.Components.Remove(item);
			item.Parent = owner;
			item.DrawOrderChanged += new ComponentDrawOrderChangedEventHandler(ComponentDrawOrderChangeEventHandler);
			base.InsertItem(index, item);
			UpdateDrawPosition(item);
		}
		void ComponentDrawOrderChangeEventHandler(object sender, ComponentDrawOrderChangedEventArgs e)
		{
			UpdateDrawPosition(e.Component);
		}
		void UpdateDrawPosition(Component Component)
		{
			int ord = Component.DrawOrder;
			int loc = Items.IndexOf(Component);
			if(inDrawOrder.Contains(loc))
				inDrawOrder.Remove(loc);
			int i = 0;
			if(ord > 0)
			{
				while (i < inDrawOrder.Count)
				{
					if(Items[inDrawOrder[i]].DrawOrder >= ord)
					{
						if(Items[inDrawOrder[i]].DrawOrder > ord) i--;
						break;
					}
					else ++i;
				}
				inDrawOrder.Insert(i,Items.IndexOf(Component));
			}
		}
		public ComponentEnumerator InDrawOrder
		{
			get { return new ComponentEnumerator(this, inDrawOrder); }
		}
		protected override void RemoveItem(int index)
		{
			Items[index].Parent = null;
			Items[index].DrawOrderChanged -= ComponentDrawOrderChangeEventHandler;
			base.RemoveItem(index);
			inDrawOrder.Clear();
			foreach (Component Component in Items)
				UpdateDrawPosition(Component);
		}
	}
}
